package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"person/models/mysql"
	"time"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserPerfectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserPerfectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserPerfectLogic {
	return &UserPerfectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 完善个人信息
func (l *UserPerfectLogic) UserPerfect(in *personrpc.UserPerfectRequest) (*personrpc.UserPerfectResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("查询失败，用户不存在")
	}

	user = mysql.User{
		Model:      gorm.Model{ID: uint(in.UserId)},
		Email:      in.Email,
		Address:    in.Address,
		Qq:         in.Qq,
		WechatCode: fmt.Sprintf("wx_%d%d", time.Now().Unix(), rand.Intn(100000)),
	}
	if err := user.UserPerfect(mysql.DB); err != nil {
		return nil, errors.New("完善信息失败")
	}

	return &personrpc.UserPerfectResponse{
		UserId: int64(user.ID),
	}, nil
}
